package cn.fz.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

/**
 * SM4加解密工具类
 */
public class SM4Utils {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 加密
     * @param data 待加密的数据
     * @param key 密钥必须16字节
     * @return 使用Base64编码输出加密结果
     */
    public static String encrypt(String data, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS7Padding", "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "SM4");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted); // 使用Base64编码输出加密结果
    }

    /**
     * 解密
     * @param encryptedData 待解密的数据
     * @param key 密钥必须16字节
     * @return 将解密后的字节数组转换为字符串
     */
    public static String decrypt(String encryptedData, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS7Padding", "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "SM4");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData); // Base64解码
        byte[] decrypted = cipher.doFinal(decodedBytes);
        return new String(decrypted, StandardCharsets.UTF_8); // 将解密后的字节数组转换为字符串
    }
}
